﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace ChatTool
{
    public partial class FormChatToOne : Form
    {
        private Point mouseDown;//鼠标按下的位置
        private FormManager formManager;
        private UserClient userClient;
        private FormFace formFace;

        private UserClient videoChatUserClient;
        private Image hisImage;//对方形象照片

        public UserClient UserClient
        {
            get { return userClient; }
            set { userClient = value; }
        }
        private bool isExit;//
        private HandleComponentDelegate handleComponentDelegate;
        private VoiceClient voiceClient;//语音聊天的包装对象

        private DesktopShare desktopShare;
        private RemoteHelpClient remoteHelpClient;

        private DateTime startdateTime;
        public FormChatToOne()
        {
            InitializeComponent();
        }

        public FormChatToOne(FormManager formManager, UserClient userClient)
        {
            InitializeComponent();
            this.formManager = formManager;
            this.userClient = userClient;
            handleComponentDelegate = ExecHandleComponent;
            this.labelName.Text = userClient.User.Name;
            this.pbHisPhoto.Image = userClient.User.Photo;
            this.labelMood.Text = userClient.User.SignWord;
            this.voiceClient = new VoiceClient(this);
            this.voiceClient.InitVoiceClient();
            this.startdateTime = DateTime.Now;
            this.BackgroundImage = new Bitmap(formManager.BackgroundImage);
            this.Text = userClient.User.Name;

            Thread receiveMsgThread = new Thread(ReceiveMsg);
            receiveMsgThread.IsBackground = true;
            receiveMsgThread.Start(userClient);
        }
        //接收连接对方发过来的消息
        private void ReceiveMsg(Object obj)
        {
            UserClient userClient = (UserClient)obj;
            while (isExit == false)
            {
                try
                {
                    string command = userClient.Br.ReadString().ToLower();
                    switch (command.ToLower())
                    {
                        case "talkcontent"://私聊内容
                            string rtf = userClient.Br.ReadString();
                            this.Invoke(handleComponentDelegate, "rtbRecord", "AddRtfString", rtf);
                            break;
                        case "logout"://对方下线
                            string logoutRtf = Tool.GetRtfString("对方已经停止了私聊!", Tool.Font, Color.DarkGray);
                            this.Invoke(handleComponentDelegate, "rtbRecord", "AddLogoutRtfString", logoutRtf);
                            return;
                        case "personimage"://对方形象秀照片
                            int personImageLen = userClient.Br.ReadInt32();
                            byte[] bs = userClient.Br.ReadBytes(personImageLen);
                            this.Invoke(handleComponentDelegate, "pbHim", "SetOppositeImage", bs);
                            break;
                        case "windowsrock"://对方发来的窗口震动
                            this.Invoke(handleComponentDelegate, "FormChatToOne", "RockWindows", "");
                            break;
                        case "helpcommand":
                            ParseHelpCommand(userClient);
                            break;
                        default:
                            break;
                    }
                }
                catch//可能 本端自己关的连接 这时 isExit=true 而 userClient也已经关闭 所以执行 userClient.br.ReadString();会出现异常 而被捕获
                {
                    if (isExit == false)//这时对方先关闭连接的情况 也就是对方的电脑突然关闭 而没有向我方发送"logout"命令
                    {
                        MessageBox.Show("对方异常下线.");
                    }
                    //自己关闭导致异常前 已经做了关闭连接后该做的事 所以这里不做其他操作
                    break;
                }
            }
        }
        private MouseAndKey mak = new MouseAndKey();//鼠标键盘模拟对象
        /// <summary>
        /// 解析对方的远程协助命令
        /// </summary>
        private void ParseHelpCommand(UserClient userClient)
        {
            string whichOne = "";
            string command = userClient.Br.ReadString().ToLower();
            try
            {
                switch (command)
                {
                    case "mousemove"://鼠标移动
                        string[] localString = userClient.Br.ReadString().Split('@');
                        int localX = int.Parse(localString[0]);
                        int localY = int.Parse(localString[1]);
                        int remoteFormHeight = int.Parse(localString[2]);
                        double rate = ((double)Screen.AllScreens[0].Bounds.Height) / remoteFormHeight;
                        mak.SetCursorPosition((int)(localX * rate), (int)(localY * rate));
                        break;
                    case "mousedown"://鼠标键的按下
                        whichOne = userClient.Br.ReadString().ToLower();
                        if (whichOne == "left")
                            mak.MouseDown(MouseAndKey.ClickOnWhat.LeftMouse);
                        else if (whichOne == "middle")
                            mak.MouseDown(MouseAndKey.ClickOnWhat.MiddleMouse);
                        else if (whichOne == "right")
                            mak.MouseDown(MouseAndKey.ClickOnWhat.RightMouse);
                        break;
                    case "mouseup"://鼠标键的抬起
                        whichOne = userClient.Br.ReadString().ToLower();
                        if (whichOne == "left")
                            mak.MouseUp(MouseAndKey.ClickOnWhat.LeftMouse);
                        else if (whichOne == "middle")
                            mak.MouseUp(MouseAndKey.ClickOnWhat.MiddleMouse);
                        else if (whichOne == "right")
                            mak.MouseUp(MouseAndKey.ClickOnWhat.RightMouse);
                        break;
                    case "keypress"://键盘键的按下即抬起
                        int keyValue = int.Parse(userClient.Br.ReadString());
                        MouseAndKey.VirtualKeys virtualKey = (MouseAndKey.VirtualKeys)(Enum.ToObject(typeof(MouseAndKey.VirtualKeys), keyValue));
                        mak.KeyPress(virtualKey);
                        break;
                    case "mousewheel"://鼠标滚轮的滚动
                        int delta = int.Parse(userClient.Br.ReadString());
                        mak.MouseWheel(delta);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        //根据某一命令处理某一控件的操作
        private delegate void HandleComponentDelegate(string componentName, string cmd, Object msg);
        private void ExecHandleComponent(string componentName, string cmd, Object msg)
        {
            //MessageBox.Show(componentName + "" + cmd + "" + msg);
            if (componentName == "rtbRecord")
            {
                if (cmd == "AddRtfString")
                {
                    string rtf = Tool.GetRtfString(userClient.User.Name + "  " + DateTime.Now.ToLongTimeString(), Tool.Font, Color.Chocolate);
                    AddRtfByClipboard(rtf);
                    AddRtfByClipboard((string)msg);
                }
                else if (cmd == "AddLogoutRtfString")
                {
                    AddRtfByClipboard((string)msg);
                }
            }
            else if (componentName == "pbHim")
            {
                if (cmd == "SetOppositeImage")
                {
                    using (MemoryStream ms = new MemoryStream((byte[])msg))
                    {
                        if (this.pbHim.Image != null)
                        {
                            this.pbHim.Image.Dispose();
                            this.pbHim.Image = null;
                        }
                        this.pbHim.Image=new Bitmap(ms);
                    }
                }
                else if (cmd == "VideoImage")
                {
                    if (pbHim.Image != null)
                    {
                        pbHim.Image.Dispose();
                        pbHim.Image = null;
                    }
                    pbHim.Image = (Image)msg;
                }
            }
            else if (componentName == "FormChatToOne")
            {
                if (cmd == "RockWindows")
                {
                    //循环三次
                    RockSomeTimes(6);
                }
            }
            else if (componentName == "pbHimAndPanelMid")
            {
                if (cmd == "RebackToOld")
                {
                    this.buttonAgree.PerformClick();
                    //this.buttonAgree.Text = "同意";
                    //this.panelMid.Visible = false;
                    //this.pbHim.Image = this.hisImage;
                }
            }
            else if (componentName == "tsbDesktopShare")
            {
                if (cmd == "SetButtonText")
                {
                    tsbDesktopShare.Text = (string)msg;
                }
            }
            else if (componentName == "tsbRemoteControl")
            {
                if (cmd == "SetButtonText")
                {
                    tsbRemoteControl.Text = (string)msg;
                }
            }
        }
        //震动窗口几次
        private void RockSomeTimes(int times)
        {
            int time = 0;
            if (Tool.peiZhiData.ContainsKey("RockVoice") == false || Tool.peiZhiData["RockVoice"] == "True")
            {
                UnmanagedMemoryStream ums = Properties.Resources.shake;
                Tool.Play(ums);
            }
            while ((++time) < times)
            {
                this.RockWindows();
            }
        }
        //处理窗口震动命令
        private void RockWindows()
        {
            int dx = 30;
            int dy = 30;
            int sleepTime = 20;
            this.Top -= dy;
            Thread.Sleep(sleepTime);
            this.Left -= dx;
            Thread.Sleep(sleepTime);
            this.Top += dy;
            Thread.Sleep(sleepTime);
            this.Left += dx;
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            Button but = sender as Button;
            string butName = but.Name;
            if (butName == "buttonClose")//关闭
            {
                NetManager.SendStringMsgToServer(userClient, "Logout");
                this.isExit = true;
                this.formManager.ChatToOneList.Remove(this);
                userClient.Close();
                if (Tool.peiZhiData.ContainsKey("SaveChatToOneRecord") == false || Tool.peiZhiData["SaveChatToOneRecord"] == "True")
                {
                    if (rtbRecord.Text.Trim() != "" && rtbRecord.Rtf != "")
                        FileOperate.WriteChatRecordToFile(userClient.User.Ip, startdateTime, rtbRecord.Rtf);//保存聊天记录
                }
                this.Close();
            }
            else if (butName == "buttonMax")//最大化
            {
                if (this.WindowState == FormWindowState.Normal)
                    this.WindowState = FormWindowState.Maximized;
                else
                    this.WindowState = FormWindowState.Normal;
            }
            else if (butName == "buttonMin")//最小化
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.mouseDown = e.Location;
            }
        }

        private void panel2_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Left += (e.X - mouseDown.X);
                this.Top += (e.Y - mouseDown.Y);
            }
        }

        private void 按Enter发送消息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //按Enter发送消息ToolStripMenuItem
            ToolStripMenuItem tsm = sender as ToolStripMenuItem;
            string name = tsm.Name;
            tsm.Checked = true;
            tsm.Enabled = false;
            if (name == "按Enter发送消息ToolStripMenuItem")
            {
                按CtrlEnter发送消息ToolStripMenuItem.Checked = false;
                按CtrlEnter发送消息ToolStripMenuItem.Enabled = true;
            }
            else
            {
                按Enter发送消息ToolStripMenuItem.Checked = false;
                按Enter发送消息ToolStripMenuItem.Enabled = true;
            }
        }
        //想聊天内容RichTextBox添加Rtf文本
        public void AddRtfByClipboard(string rtf)
        {
            rtbRecord.ReadOnly = false;
            rtbRecord.AppendText(" ");
            rtbRecord.ScrollToCaret();
            Clipboard.SetData(DataFormats.Rtf, rtf);
            if (rtbRecord.CanPaste(DataFormats.GetFormat(DataFormats.Rtf)))
            {
                rtbRecord.Paste(DataFormats.GetFormat(DataFormats.Rtf));
            }
            rtbRecord.AppendText(Environment.NewLine);//加这句代码是为了让下面的那句代码起作用
            rtbRecord.ScrollToCaret();
            rtbRecord.ReadOnly = true;
        }
        //发送消息按钮
        private void tsbSend_ButtonClick(object sender, EventArgs e)
        {
            if (rtbWrite.Text == "")
                return;
            try
            {
                //向自己的聊天内容框加聊天内容
                string rtf = Tool.GetRtfString(this.formManager.UserOwn.Name + "  " + DateTime.Now.ToLongTimeString(), Tool.Font, Color.DarkGray);
                AddRtfByClipboard(rtf);
                AddRtfByClipboard(rtbWrite.Rtf);
                //向对方的聊天内容框加聊天内容
                NetManager.SendStringMsgToServer(userClient, "TalkContent");
                NetManager.SendStringMsgToServer(userClient, rtbWrite.Rtf);

                this.rtbWrite.Clear();
                this.rtbWrite.Focus();

            }
            catch (Exception)
            {
                this.rtbWrite.Clear();
                this.rtbWrite.Focus();
                this.Text = "对方不在线";
            }
        }
        //表示传送文件的数目
        private int sumFile;
        //递归是否继续的标志
        private bool isGoOn;
        // 响应鼠标的拖放事件
        private void FormChatToOne_DragDrop(object sender, DragEventArgs e)
        {
            string[] fileNames = null;
            if (e.Data.GetDataPresent("FileNameW"))//判断拖放的对象中是不是有FileNameW格式的文件名
            {
                fileNames = (string[])e.Data.GetData("FileNameW");
            }

            if (fileNames.Length > 0)
            {
                foreach (string fileName in fileNames)
                {
                    //MessageBox.Show(fileName);
                    string format = fileName.Substring(fileName.LastIndexOf('.') + 1);//获取文件名的格式后缀
                    if (format.Equals("gif", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("jpg", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("jpeg", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("bmp", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("png", StringComparison.CurrentCultureIgnoreCase))
                    {
                        Image image = Image.FromFile(fileName);
                        Clipboard.SetImage(image);
                        if (Clipboard.ContainsImage())
                        {
                            if (rtbWrite.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap)))
                            {
                                rtbWrite.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
                            }
                        }
                        image.Dispose();//释放原来的图片对象
                        image = null;
                    }
                    else
                    {
                        this.sumFile = 0;
                        this.isGoOn = true;
                        TransferFile(fileName);
                        //MessageBox.Show(sumFile + "");
                    }
                }
            }
        }
        // 传送文件 可以文件夹嵌套
        private void TransferFile(string fileName)
        {
            if (File.Exists(fileName))//若是文件
            {
                this.sumFile++;
                FileTransfer fileTransfer = new FileTransfer(this, fileName);
                fileTransfer.Send();
                if (sumFile > 99)
                {
                    MessageBox.Show("文件夹中的文件数大于100，请分批传送或者压缩后再传送!");
                    this.isGoOn = false;
                    return;
                }
            }
            else//若是文件夹
            {
                foreach (string fn in Directory.GetFileSystemEntries(fileName))
                {
                    if (this.isGoOn == false)
                        return;
                    TransferFile(fn);
                }
            }
        }
        // 响应鼠标拖放对方进入拖放响应区 拖放最终要完成的操作 即设置e.Effect的枚举值
        private void FormChatToOne_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("FileNameW"))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
        //清空文本框
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.rtbWrite.Clear();
            this.rtbWrite.Focus();
        }

        private void panel2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
                this.WindowState = FormWindowState.Maximized;
            else
                this.WindowState = FormWindowState.Normal;
        }
        //设置个人形象秀
        private void pictureBox2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            openFileDialog.Filter = "(图像文件)*.jpg;*.jpeg;*.bmp;*.png;*.gif|*.jpg;*.jpeg;*.bmp;*.png;*.gif";
            openFileDialog.FileName = "选择图像文件";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (Stream stream = openFileDialog.OpenFile())
                    {
                        this.pbMe.Image = new Bitmap(stream);//设置自己形象面板中的形象

                        stream.Seek(0, SeekOrigin.Begin);
                        //将自己设置的形象图片发送给对方 以便对方的 对方形象面板中可以看到自己的形象秀
                        byte[] bs = new byte[stream.Length];
                        stream.Read(bs, 0, (int)stream.Length);

                        NetManager.SendStringMsgToServer(userClient, "PersonImage");
                        NetManager.SendBytesMsgToServer(userClient, bs);
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show("设置个人形象秀时异常: " + ee.Message);
                }
            }
        }
        //快捷键发送消息
        private void rtbWrite_KeyDown(object sender, KeyEventArgs e)
        {
            if (this.按Enter发送消息ToolStripMenuItem.Checked == true)
            {
                if (e.Control == false && e.KeyCode == Keys.Enter)
                {
                    tsbSend.PerformButtonClick();
                    e.Handled = true;
                }
            }
            else
            {
                if (e.Control == true && e.KeyCode == Keys.Enter)
                {
                    tsbSend.PerformButtonClick();
                    e.Handled = true;
                }
            }
        }
        //初始化
        private void FormChatToOne_Load(object sender, EventArgs e)
        {
            //如何获得系统字体列表
            System.Drawing.Text.InstalledFontCollection fonts = new System.Drawing.Text.InstalledFontCollection();
           //System.Drawing.FontFamily initFamily;
            foreach (System.Drawing.FontFamily family in fonts.Families)
            {
                tscbFontFamily.Items.Add(family.Name);
            }
            tscbFontFamily.SelectedItem = "宋体";
            tscbFontSize.SelectedIndex = 3;
        }
        //字体设置
        private void tscbFontFamily_SelectedIndexChanged(object sender, EventArgs e)
        {
            string fontFamily = tscbFontFamily.SelectedItem.ToString();
            float fontSize = 11.0F;
            if (tscbFontSize.SelectedItem != null)
                fontSize = float.Parse(tscbFontSize.SelectedItem.ToString());
            this.rtbWrite.Font = new Font(fontFamily, fontSize, rtbWrite.Font.Style);
        }
        //字体设置
        private void tscbFontSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            string fontFamily = tscbFontFamily.SelectedItem.ToString();
            float fontSize = float.Parse(tscbFontSize.SelectedItem.ToString());
            this.rtbWrite.Font = new Font(fontFamily, fontSize, rtbWrite.Font.Style);
        }
        //字体设置
        private void tsbAddRough_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            string name = tsb.Name;
            if (name == "tsbAddRough")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Bold;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbIncline")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Italic;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbUnderline")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Underline;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbStrikeout")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Strikeout;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbFontColor")
            {
                if (colorDialog.ShowDialog() == DialogResult.OK)
                    rtbWrite.ForeColor = colorDialog.Color;
            }
            else if (name == "tsbSetFont")
            {
                this.toolStripFont.Visible = !this.toolStripFont.Visible;
            }
            else if (name == "tsbFaceManager")
            {
                if (formFace == null)
                {
                    formFace = new FormFace(this);
                    formFace.Top = this.Top + this.tsMid.Top - formFace.Height + 90;
                    formFace.Left = this.Left + 10;
                    formFace.Show(this);
                }
                else
                {
                    formFace.Top = this.Top + this.tsMid.Top - formFace.Height + 90;
                    formFace.Left = this.Left + 10;
                    formFace.Visible = !formFace.Visible;
                }
            }
            else if (name == "tsbFormRock")//窗口震动
            {
                this.RockSomeTimes(6);
                NetManager.SendStringMsgToServer(userClient, "WindowsRock");
                tsb.Enabled = false;
                this.timer.Start();
            }
            else if (name == "tsbSendPicture")
            {
                GetPictureFromComputer();
            }
            
        }
        private void ttssbSendCutPicture_ButtonClick(object sender, EventArgs e)
        {
            if (截图时隐藏聊天窗口ToolStripMenuItem.Checked)
                this.Visible = false;
            new FormSetCopyRegion(this).Show();   
        }
        /// <summary>
        /// 处理截图的图片
        /// </summary>
        public void HandleBitmap(Bitmap bitmap)
        {
            AddFaceToRbWrite(bitmap);
        }
        //获取电脑中的图片
        private void GetPictureFromComputer()
        {
            openFileDialog.Filter = "(图像文件)*.jpg;*.jpeg;*.bmp;*.png;*.gif|*.jpg;*.jpeg;*.bmp;*.png;*.gif";
            openFileDialog.FileName = "选择图像文件";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (Stream stream = openFileDialog.OpenFile())
                    {
                        Bitmap sendImage = new Bitmap(stream);
                        AddFaceToRbWrite(sendImage);
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show("发送图片时异常: " + ee.Message);
                }
            }
        }
        //发送窗口震动的计时器
        private void timer_Tick(object sender, EventArgs e)
        {
            this.timer.Stop();
            this.tsbFormRock.Enabled = true;//5秒后开启
        }

        private void 截图时隐藏聊天窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsm = sender as ToolStripMenuItem;
            string name = tsm.Name;
            if (name == "截图时隐藏聊天窗口ToolStripMenuItem")
            {
                tsm.Checked = !tsm.Checked;
            }
        }
        /// <summary>
        /// 将选中的表情加到RichTextBox发送栏中
        /// </summary>
        public void AddFaceToRbWrite(Image sendImage)
        {
            Clipboard.SetImage(sendImage);//将表情图片放入系统剪贴板中
            if (Clipboard.ContainsImage())
            {
                if (rtbWrite.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap)))
                {
                    rtbWrite.Paste(DataFormats.GetFormat(DataFormats.Bitmap));//将剪贴板中的图片加入到发送面板中
                }
            }
            sendImage.Dispose();//释放原来的图片
            sendImage = null;
        }
        private Rectangle shareRegion;
        /// <summary>
        /// 共享桌面的区域
        /// </summary>
        public Rectangle ShareRegion
        {
            get { return shareRegion; }
            set { shareRegion = value; }
        }
        //处理一些附加功能
        private void tsbFileTransfer_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            string name = tsb.Name;
            if (name == "tsbFileTransfer")//文件传送
            {
                openFileDialog.Multiselect = true;
                if(openFileDialog.ShowDialog()==DialogResult.OK)
                {
                    foreach (string fileName in openFileDialog.FileNames)
                    {
                        FileTransfer fileTransfer = new FileTransfer(this, fileName);
                        fileTransfer.Send();
                    }
                }
                openFileDialog.Multiselect = false;
            }
            else if (name == "tsbDesktopShare")//桌面共享
            {
                if (tsb.Text == "桌面共享")
                {
                    if (tsbVideoChat.Enabled == false)
                    {
                        MessageBox.Show("视频聊天功能已经开启,视频聊天和桌面共享不能同时开启!");
                        return;
                    }
                    desktopShare = new DesktopShare(this);
                    UserClient desktopShareUserClient = desktopShare.ConnectServer();
                    if (desktopShareUserClient == null)
                        MessageBox.Show("连接服务器失败,可能对方服务器未开启.");
                    else
                    {
                        FormSelectShareRegion selectRegion = new FormSelectShareRegion(this, desktopShareUserClient);
                        selectRegion.Show();
                        tsb.Text = "停止共享";
                    }
                }
                else
                {
                    tsb.Text = "桌面共享";
                    desktopShare.Close();
                }
            }
            else if (name == "tsbVoiceChat")//语音聊天
            {
                if (tsb.Text == "语音聊天")
                {
                    voiceClient.BeginVoiceTalk();
                    //NetManager.SendStringMsgToServer(userClient, "PhoneCall");
                    tsb.Text = "停止语聊";
                }
                else
                {
                    voiceClient.StopVoiceTalk();
                    tsb.Text = "语音聊天";
                }
            }      
            else if (name == "tsbVideoChat")//视频聊天
            {
                tsb.Enabled = false;
                FormVideoControl video = new FormVideoControl(this);
                video.Show();
            }
            else if (name == "tsbRemoteControl")//远程协助
            {
                if (tsbRemoteControl.Text == "远程协助")
                {
                    if (MessageBox.Show("确实要请求对方的远程协助吗?", "温馨提示!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        remoteHelpClient = new RemoteHelpClient(this);
                        remoteHelpClient.StartConnectServer();
                    }
                }
                else
                {
                    if (MessageBox.Show("确实要停止远程协助吗?", "温馨提示!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        remoteHelpClient.StopRemoteHelpClient();
                    }
                }
            }
        }
        private delegate void AddOrDeleteToolStripDelegate(string cmd, ToolStrip ts);
        /// <summary>
        /// 添加文件传送提示控件
        /// </summary>
        public void AddOrDeleteToolStripToPanel(string cmd, ToolStrip ts)
        {
            if (panelMe.InvokeRequired)
            {
                this.Invoke(new AddOrDeleteToolStripDelegate(AddOrDeleteToolStripToPanel), cmd, ts);
            }
            else
            {
                if (cmd == "Add")
                {
                    this.pbMe.Visible = false;
                    this.panelMe.Controls.Add(ts);
                }
                else if (cmd == "Delete")
                {
                    this.panelMe.Controls.Remove(ts);
                    if (panelMe.Controls.Count == 1)
                        this.pbMe.Visible = true;
                }
            }
        }
        /// <summary>
        /// 处理文件接收命令
        /// </summary>
        public void HandleTransferFileCmd(ChatTool.UserClient userClient)
        {
            FileReceive fileReceive = new FileReceive(userClient, this);//文件接收
            fileReceive.Receive();
        }
        /// <summary>
        /// 设置Button的状态
        /// </summary>
        public void SetButtonEnabled(string buttonName, bool value)
        {
            if (buttonName == "tsbVideoChat")
                this.tsbVideoChat.Enabled = value;
        }
        /// <summary>
        /// 处理视频聊天命令
        /// </summary>
        public void HandleVideoTalkCmd(ChatTool.UserClient userClient)
        {
            this.panelMid.Visible = true;
            this.videoChatUserClient = userClient;
            string rtf = Tool.GetRtfString("对方请求共享他的聊天视频,点击右边的按钮处理.", Tool.Font, Color.Brown);
            this.AddRtfByClipboard(rtf);
        }

        private void buttonAgree_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            string text = button.Text;
            if (text == "同意")
            {
                button.Text = "停止";
                this.buttonRefuse.Enabled = false;
                this.hisImage = new Bitmap(pbHim.Image);
                Thread videoChatThread = new Thread(VideoReceive);
                videoChatThread.IsBackground = true;
                videoChatThread.Start();
                NetManager.SendStringMsgToServer(videoChatUserClient, "Agree");
            }
            else if (text == "拒绝")
            {
                NetManager.SendStringMsgToServer(videoChatUserClient, "Refuse");
                videoChatUserClient.Close();
                this.panelMid.Visible = false;
            }
            else if (text == "停止")
            {
                button.Text = "同意";
                this.buttonRefuse.Enabled = true;
                NetManager.SendStringMsgToServer(videoChatUserClient, "Stop");
                videoChatUserClient.Close();
                this.panelMid.Visible = false;
                this.pbHim.Image = this.hisImage;
            }
        }
        private void VideoReceive()
        {
            while (true)
            {
                try
                {
                    int imageLen = this.videoChatUserClient.Br.ReadInt32();
                    byte[] bs = this.videoChatUserClient.Br.ReadBytes(imageLen);
                    using (MemoryStream ms = new MemoryStream(bs))
                    {
                        this.Invoke(handleComponentDelegate, "pbHim", "VideoImage", new Bitmap(ms));
                    }
                }
                catch (Exception)
                {
                    videoChatUserClient.Close();
                    try
                    {
                        this.Invoke(handleComponentDelegate, "pbHimAndPanelMid", "RebackToOld", "");
                    }
                    catch (Exception){ }
                    return;
                }
            }
        }

        private void pbHim_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.splitContainer1.Panel1Collapsed = !this.splitContainer1.Panel1Collapsed;
            //this.tableLayoutPanel5.RowStyles[2].SizeType
            if (this.tableLayoutPanel5.RowStyles[2].Height == 0.0F)
            {
                this.tableLayoutPanel5.RowStyles[0].Height = (this.tableLayoutPanel5.Height - 33) * 0.6F;
                this.tableLayoutPanel5.RowStyles[2].Height = (this.tableLayoutPanel5.Height - 33) * 0.4F;
            }
            else
                this.tableLayoutPanel5.RowStyles[2].Height = 0.0F;
        }
        /// <summary>
        /// 处理接收到的对方桌面截图
        /// </summary>
        public void ShowDesktopShareImage(Bitmap bitmap)
        {
            this.Invoke(handleComponentDelegate, "pbHim", "VideoImage", bitmap);
        }
        /// <summary>
        /// 处理桌面共享命令
        /// </summary>
        public void HandleDesktopShareCmd(ChatTool.UserClient userClient)
        {
            this.panelMid.Visible = true;
            this.videoChatUserClient = userClient;
            string rtf = Tool.GetRtfString("对方请求共享他的桌面,点击右边的按钮处理.", Tool.Font, Color.Brown);
            this.AddRtfByClipboard(rtf);
        }
        /// <summary>
        /// 设置Button的Text属性
        /// </summary>
        public void SetButtonText(string buttonName, string text)
        {
            this.Invoke(handleComponentDelegate, buttonName, "SetButtonText", text);
        }
        /// <summary>
        /// 处理远程协助命令
        /// </summary>
        public void HandleRemoteHelpCmd(UserClient userClient)
        {
            if (MessageBox.Show("对方请求你的远程协助,同意吗?\r\n注意:  正在远程协助时,你可以按[Esc]停止远程协助.\r\n         同时,你可以按[Ctrl+Enter]来切换全屏和半屏.", "温馨提示!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                NetManager.SendStringMsgToServer(userClient, "Refuse");
                userClient.Close();
                return;
            }
            NetManager.SendStringMsgToServer(userClient, "Agree");
            FormRemoteHelpDesktop remoteHelp = new FormRemoteHelpDesktop(userClient, this);
            remoteHelp.Show();
        }

        private void FormChatToOne_MouseEnter(object sender, EventArgs e)
        {
            this.Activate();
        }

        private void labelName_MouseEnter(object sender, EventArgs e)
        {
            Font font = this.labelName.Font;
            this.labelName.Font = new Font(font.FontFamily, font.Size, font.Style ^ FontStyle.Underline);
            font.Dispose();
            font = null;
        }

        private void labelName_MouseLeave(object sender, EventArgs e)
        {
            Font font = this.labelName.Font;
            this.labelName.Font = new Font(font.FontFamily, font.Size, font.Style ^ FontStyle.Underline);
            font.Dispose();
            font = null;
        }

        private void labelName_MouseClick(object sender, MouseEventArgs e)
        {
            FormHisInfo formHisInfo = new FormHisInfo(this);
            formHisInfo.Show(this);
        }
        //查看消息记录
        private void tsbMsgRecord_Click(object sender, EventArgs e)
        {
            FormChatRecordManager formChatRecordManager = new FormChatRecordManager(userClient.User.Ip);
            formChatRecordManager.Show();
        }
        private delegate void AddWaringInfoToRtContentDelegate(string waringInfo);
        public void AddWaringInfoToRtContent(string waringInfo)
        {
            if (this.rtbRecord.InvokeRequired)
            {
                AddWaringInfoToRtContentDelegate d = AddWaringInfoToRtContent;
                this.Invoke(d, waringInfo);
            }
            else
            {
                string rtf = Tool.GetRtfString(waringInfo, Tool.Font, Color.Brown);
                this.AddRtfByClipboard(rtf);
            }
        }
    }
}
